var Emitter = require('emitter');
var ArrayMgr = require('arraymgr');

function AnimationMgr() {
  Emitter.call(this);
  this.isAnimating = false;
  this.timeout = 1000 / 60;
  this.animations = new ArrayMgr();
}

AnimationMgr.prototype = new Emitter();

AnimationMgr.prototype.add = function(ea) {
  this.animations.add(ea);
  ea.animate();
  var self = this;
  ea.on('end', function() {
    self.animations.rm(ea);
  });
  if (!this.isAnimating) {
    this.isAnimating = true;
    this.step();
  }
};

AnimationMgr.prototype.rm = function(ea) {
  this.animations.rm(ea);
};

AnimationMgr.prototype.step = function() {
  var d = Date.now();
  this.animations.iterate(function(a) {
    a.step(d);
  });
  if (this.animations.length() !== 0) {
    var self = this;
    setTimeout(function() {
      self.step();
    }, this.timeout);
  } else {
    this.isAnimating = false;
  }
};

module.exports = AnimationMgr;
